package com.kun.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.entity.SysRole;
import com.kun.entity.SysRoleMenu;
import com.kun.mapper.SysRoleMapper;
import com.kun.mapper.SysRoleMenuMapper;
import com.kun.service.SysRoleService;
import com.kun.vo.SysRolePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kun.li
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public List<SysRole> selectSysRole(String userId) {
        return sysRoleMapper.selectSysRole(userId);
    }

    @Override
    @Transactional
    public Boolean assignmentPermission(SysRolePermission sysRolePermission) {
        String roleId = sysRolePermission.getRoleId();
        sysRoleMenuMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId, roleId));
        List<String> menuIds = sysRolePermission.getMenuIds();
        if (CollUtil.isNotEmpty(menuIds)) {
            List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
            for (String menuId : menuIds) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenus.add(sysRoleMenu);
            }
            sysRoleMenuMapper.batchInsert(sysRoleMenus);
        }
        return true;
    }
}
